package com.atwj.Service.impl;

import com.atwj.Service.OrderService;
import com.atwj.dao.BookDao;
import com.atwj.dao.OrderDao;
import com.atwj.dao.OrderItemDao;
import com.atwj.dao.impl.BookDaoImpl;
import com.atwj.dao.impl.OrderDaoImpl;
import com.atwj.dao.impl.OrderItemDaoImpl;
import com.atwj.entity.*;

import java.util.Date;
import java.util.Map;

/**
 * @author 吴先森
 * @description:
 * @create 2022-04-01 19:28
 */
public class OrderServiceImpl implements OrderService {
    private OrderDao orderDao = new OrderDaoImpl();
    private OrderItemDao orderItemDaoImpl = new OrderItemDaoImpl();
    private BookDao bookDao = new BookDaoImpl();

    @Override
    public String createOrder(Cart cart, Integer userId) {
        //订单号====唯一性  （利用时间戳）
        String orderId = System.currentTimeMillis() + "" + userId;
        //创建一个订单对象
        Order order = new Order(orderId, new Date(), cart.getTotalPrice(), 0, userId);
        //保存订单
        orderDao.saveOrder(order);
        //遍历购物车中每个商品项转换为订单保存到数据库
        for (Map.Entry<Integer, CartItem> entry : cart.getItems().entrySet()) {
            CartItem cartItem = entry.getValue();
            OrderItem orderItem = new OrderItem(null, cartItem.getName(), cartItem.getCount(), cartItem.getPrice(), cartItem.getTotalPrice(), orderId);
            orderItemDaoImpl.saveOrderItem(orderItem);

            //更新库存和销量
            Book book = bookDao.queryBookByid(cartItem.getId());
            book.setSales(book.getSales() + cartItem.getCount());
            book.setStock(book.getStock() - cartItem.getCount());
            bookDao.updateBook(book);
        }
        cart.clear();
        return orderId;
    }
}
